package com.enation.app.javashop.consumer.job.execute.impl;

import com.enation.app.javashop.consumer.job.execute.EveryDayExecute;
import com.enation.app.javashop.consumer.job.execute.EveryFiveMinExecute;
import com.enation.app.javashop.consumer.job.execute.EveryHourExecute;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.client.trade.ShetuanClient;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.core.goodssearch.service.ShetuanSearchManager;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dto.MemberQueryParam;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanOperateManager;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.DateUtil;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 社团团购活动定时开始结束
 */
@Component
public class ShetuanJob implements EveryDayExecute, EveryHourExecute {

    protected final Log logger = LogFactory.getLog(this.getClass());


    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private ShetuanOperateManager shetuanOperateManager;

    @Autowired
    private MemberManager memberManager;

    @Autowired
    private Cache cache;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    /**
    /**
     * 每小时执行
     */
    @Override
    public void everyHour() {
        try {
            this.logger.info("-----自动开启Or结束 社区团购活动 执行-----");
            //long startOfTodDay = DateUtil.startOfTodDay();
            long currentTime=DateUtil.getDateline();

            // 结束活动（已上线）
            String sql = "select * from es_shetuan  where end_time<=? and status =" + ShetuanStatusEnum.ON_LINE.getIndex();
            List<ShetuanDO> shetuanEndList = daoSupport.queryForList(sql, ShetuanDO.class, currentTime);
            if (!CollectionUtils.isEmpty(shetuanEndList)) {
                for (ShetuanDO shetuanDO : shetuanEndList) {
                    shetuanOperateManager.offLine(shetuanDO.getShetuanId());
                }
            }

            // 开始活动（待上线）
           sql = "select * from es_shetuan  where start_time<=?  and end_time >= ? and status =" + ShetuanStatusEnum.NEW.getIndex();
            List<ShetuanDO> shetuanStartList = daoSupport.queryForList(sql, ShetuanDO.class,currentTime,currentTime );
            if (!CollectionUtils.isEmpty(shetuanStartList)) {
                for (ShetuanDO shetuanDO : shetuanStartList) {
                    shetuanOperateManager.onLine(shetuanDO.getShetuanId());
                }
            }


        } catch (Exception e) {
            this.logger.error("自动开启Or结束 社区团购活动 异常：", e);
        }
    }

    /**
     * 每天执行 00：00：00
     */
    @Override
    public void everyDay() {
        try {
            this.logger.info("-----删除所有会员 社区团购购物车商品 执行-----");
            int maxPageSize=50;
            Page page = getPage(1,1);
            MemberQueryParam memberQueryParam;
            Integer total = Math.toIntExact(page.getDataTotal());
            Integer pageCount=total/maxPageSize+1;

            for (int i = 1; i <=pageCount; i++) {
                memberQueryParam = new MemberQueryParam();
                memberQueryParam.setPageNo(i);
                memberQueryParam.setPageSize(maxPageSize);
                page = memberManager.list(memberQueryParam);
                List<Member> memberList = page.getData();
                for (Member member : memberList) {
                    // 每日清除社区团购购物车
                    cache.remove(CachePrefix.CART_SHETUAN_DATA_PREFIX.getPrefix() + member.getMemberId());
                    // 每日清除立即购买购物车
                    cache.remove(CachePrefix.BUY_NOW_SHETUAN_DATA_PREFIX.getPrefix() + member.getMemberId());
                    // 每日清除单品促销信息
                    cache.remove(CachePrefix.CART_PROMOTION_PREFIX.getPrefix() + member.getMemberId());
                }

            }
        } catch (Exception e) {
            this.logger.error("删除当日失效的社区团购购物车商品：", e);
        }
        try {
            //    删除社区团购商品购买数量统计
            Set<String> keys = redisTemplate.keys(CachePrefix.ST_BUY_NUM.getPrefix() + "*");
            redisTemplate.delete(keys);
        } catch (Exception e) {
            this.logger.error("删除当日社区团购商品购买数量：", e);        }
    }

    private Page getPage(Integer pageNo,Integer pageSize) {
        MemberQueryParam memberQueryParam = new MemberQueryParam();
        memberQueryParam.setPageNo(pageNo);
        memberQueryParam.setPageSize(pageSize);
        return memberManager.list(memberQueryParam);
    }
    //
    //@Override
    //public void everyHour() {
    //    try {
            //this.logger.info("-----社区团购每小时 执行-----");
            //// 查询商品基础信息
            //String sql = "select * from es_shetuan  where status =" + ShetuanStatusEnum.ON_LINE.getIndex();
            //List<ShetuanDO> shetuanStartList = daoSupport.queryForList(sql, ShetuanDO.class);
            //
            //for (ShetuanDO shetuanDO : shetuanStartList) {
            //    List<ShetuanGoodsDO> goods = shetuanGoodsManager.getByShetuanId(shetuanDO.getShetuanId());
            //    List<Integer> goodsIds = goods.stream().map(ShetuanGoodsDO::getGoodsId).distinct().collect(Collectors.toList());
            //
            //    Map<Integer, Map<String, Object>> goodsIndex = getGoods(goodsIds.toArray(new Integer[goodsIds.size()]));
            //    for (ShetuanGoodsDO good : goods) {
            //        ShetuanGoodsVO shetuanGoodsVO = new ShetuanGoodsVO(shetuanDO, good);
            //        shetuanSearchManager.addIndex(shetuanGoodsVO, goodsIndex.get(shetuanGoodsVO.getGoodsId()));
            //    }
            //}
    //    } catch (Exception e) {
    //        this.logger.error("社区团购每小时：", e);
    //    }
    //}



    private Map<Integer, Map<String, Object>> getGoods(Integer[] goodsIds) {
        List<Map<String, Object>> goodsList = goodsClient.getGoodsAndParams(goodsIds);
        Map<Integer, Map<String, Object>> goodsIndex = Maps.newHashMap();
        for (Map<String, Object> goods : goodsList) {
            goodsIndex.put((Integer) goods.get("goods_Id"),goods);
        }
        return goodsIndex;
    }
}
